Máster en Data Science UAH

Tasador de viviendas de alquiler vacacional en Madrid

Notebook #3 - Estudio de la localización

Alumno: Héctor Mateos Oblanca
Tutor: Daniel Rodríguez Pérez

Intro

In [1]:
city = 'madrid'
month = '201909'
filename_in = 'src/data/' + city + '-' + month + '-listings-CLEAN.csv'
In [2]:
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, HTML
from statsmodels.stats.outliers_influence import variance_inflation_factor
import featuretools as ft
import uuid
import s2sphere as s2
import random
 
import catboost as cb
from kmodes.kmodes import KModes
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score, cross_val_predict 
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error

import scipy.spatial as spatial
import plotly.express as px
import chart_studio.plotly as py
import plotly.graph_objs as go
from plotly.offline import iplot, init_notebook_mode

%run src/utils.py
In [3]:
coefs = {}
metrics = {}

def collect_results(columns, model, method, r2, mae, mse, skip_coef=True):
    # coefs
    if skip_coef != True:
        method_coefs = {}
        if hasattr(model, '__intercept'):
            method_coefs['__intercept'] = model.intercept_
        
        for i in range(len(columns.values)):
            method_coefs[columns.values[i]] = abs(model.coef_[i])
        coefs[method] = method_coefs
        df_coefs = pd.DataFrame(coefs)
        df_coefs = df_coefs.sort_values(by=method, ascending=False)
        display(df_coefs)
    
    # metrics
    metrics[method] = {
        'R2':r2.round(3),
        'MAE':mae.round(3),
        'MSE':mse.round(3)
    }
    
    display(pd.DataFrame(metrics))

def print_feature_importances(method, importances, df):
    feature_score = pd.DataFrame(list(zip(df.dtypes.index, importances)), columns=['Feature','Score'])
    feature_score = feature_score.sort_values(by='Score', 
                                              ascending=True, 
                                              inplace=False, 
                                              kind='quicksort', 
                                              na_position='last')
    
    fig = go.Figure(
        go.Bar(
            x=feature_score['Score'],
            y=feature_score['Feature'],
            orientation='h'
        )
    )
    
    fig.update_layout(
        title=method + " Feature Importance Ranking",
        height=25*len(feature_score)
    )
    
    fig.show()

Carga del dataset

In [4]:
df = pd.read_csv(filename_in)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 13363 entries, 0 to 13362
Data columns (total 61 columns):
host_response_time                      13363 non-null object
latitude                                13363 non-null float64
longitude                               13363 non-null float64
property_type                           13363 non-null object
room_type                               13363 non-null object
accommodates                            13363 non-null int64
bathrooms                               13363 non-null float64
bedrooms                                13363 non-null float64
price                                   13363 non-null float64
security_deposit                        13363 non-null float64
cleaning_fee                            13363 non-null float64
guests_included                         13363 non-null int64
extra_people                            13363 non-null float64
minimum_nights_avg_ntm                  13363 non-null float64
maximum_nights_avg_ntm                  13363 non-null float64
number_of_reviews                       13363 non-null int64
number_of_reviews_ltm                   13363 non-null int64
first_review                            13363 non-null object
last_review                             13363 non-null object
review_scores_rating                    13324 non-null float64
review_scores_accuracy                  13325 non-null float64
review_scores_cleanliness               13326 non-null float64
review_scores_checkin                   13326 non-null float64
review_scores_communication             13326 non-null float64
review_scores_location                  13326 non-null float64
review_scores_value                     13326 non-null float64
instant_bookable                        13363 non-null int64
cancellation_policy                     13363 non-null object
reviews_per_month                       13363 non-null float64
district                                13363 non-null object
neighbourhood                           13363 non-null object
has_wifi                                13363 non-null int64
has_essentials                          13363 non-null int64
has_kitchen                             13363 non-null int64
has_heating                             13363 non-null int64
has_washer                              13363 non-null int64
has_hangers                             13363 non-null int64
has_tv                                  13363 non-null int64
has_hair_dryer                          13363 non-null int64
has_iron                                13363 non-null int64
has_shampoo                             13363 non-null int64
has_laptop_friendly_workspace           13363 non-null int64
has_air_conditioning                    13363 non-null int64
has_hot_water                           13363 non-null int64
has_elevator                            13363 non-null int64
has_refrigerator                        13363 non-null int64
has_dishes_and_silverware               13363 non-null int64
has_microwave                           13363 non-null int64
has_bed_linens                          13363 non-null int64
has_no_stairs_or_steps_to_enter         13363 non-null int64
has_coffee_maker                        13363 non-null int64
has_cooking_basics                      13363 non-null int64
has_family/kid_friendly                 13363 non-null int64
has_long_term_stays_allowed             13363 non-null int64
has_first_aid_kit                       13363 non-null int64
has_oven                                13363 non-null int64
has_stove                               13363 non-null int64
has_license                             13363 non-null int64
activity_months                         13363 non-null float64
income_med_occupation                   13363 non-null float64
price_med_occupation_per_accommodate    13363 non-null float64
dtypes: float64(21), int64(32), object(8)
memory usage: 6.2+ MB

Descarte de características

In [5]:
useful_cols = [
    'accommodates',
    'bathrooms',
    'bedrooms',
    'cancellation_policy',
    'cleaning_fee',
    'extra_people',
    'guests_included',
    'has_air_conditioning',
    'has_bed_linens',
    'has_coffee_maker',
    'has_cooking_basics',
    'has_dishes_and_silverware',
    'has_elevator',
    'has_essentials',
    'has_family/kid_friendly',
    'has_first_aid_kit',
    'has_hair_dryer',
    'has_hangers',
    'has_heating',
    'has_hot_water',
    'has_iron',
    'has_kitchen',
    'has_laptop_friendly_workspace',
    'has_license',
    'has_long_term_stays_allowed',
    'has_microwave',
    'has_no_stairs_or_steps_to_enter',
    'has_oven',
    'has_refrigerator',
    'has_shampoo',
    'has_stove',
    'has_tv',
    'has_washer',
    'has_wifi',
    'instant_bookable',
    'latitude',
    'longitude',
    'maximum_nights_avg_ntm',
    'minimum_nights_avg_ntm',
    'neighbourhood',
    'price',
    'property_type',
    'room_type',
    'security_deposit'
]

useless_cols = [
    'district',
    'income_med_occupation',
    'activity_months',
    'host_response_time',
    'first_review',
    'last_review',
    'number_of_reviews',
    'number_of_reviews_ltm',
    'review_scores_rating',
    'review_scores_accuracy',
    'review_scores_cleanliness',
    'review_scores_checkin',
    'review_scores_communication',
    'review_scores_location',
    'review_scores_value',
    'reviews_per_month'
]

highly_corr_cols = [
    'has_refrigerator', 
    'host_verified_by_selfie'
]

df.drop([*useless_cols, *highly_corr_cols], axis=1, errors='ignore', inplace=True)
df.shape
Out[5]:
(13363, 44)

Nuevas características de localización calculadas

Distancia a puntos de interés

Se calcula para cada propiedad la distancia en kilómetros a diferentes puntos de interés turístico de la ciudad.

In [6]:
pois = [    
    {'name':'sol', 'coord':(40.4146500, -3.7004000)},
    {'name':'plaza-mayor', 'coord':(40.415511, -3.7074009)},
    {'name':'palacio-real', 'coord':(40.417955, -3.714312)},
    {'name':'aeropuerto-barajas', 'coord':(40.472222222222, -3.5608333333333)},
    {'name':'estacion-atocha', 'coord':(40.4040200, -3.6882300)},
    {'name':'estacion-chamartin', 'coord':(40.4718400, -3.6824800)},
    {'name':'estacion-autobuses', 'coord':(40.395556, -3.678194)},
    {'name':'museo-prado', 'coord':(40.4137818, -3.6921271)},
    {'name':'plaza-toros-ventas', 'coord':(40.430831, -3.6632802)},
    {'name':'wizink-center', 'coord':(40.423889, -3.671814)},
    {'name':'estadio-metropolitano', 'coord':(40.436111, -3.599444)},
    {'name':'estadio-bernabeu', 'coord':(40.4530100, -3.6882900)},
    {'name':'casa-de-campo', 'coord':(40.4233, -3.7586)},
    {'name':'san-francisco-el-grande', 'coord':(40.4105, -3.7144)},
    {'name':'ifema', 'coord':(40.4674, -3.6169)}
]
In [7]:
for poi in pois:
    df['dist_' + poi['name']] = df.apply(
        lambda r: get_haversine_distance(
            r['latitude'], 
            r['longitude'], 
            poi['coord']), 
        axis=1)

Clustering de barrios

La característica neighbourhood tiene una cardinalidad muy alta que puede conducir a sobreajuste puesto que en algunos barrios hay pocos datos. Se propone, utilizando clusterización, una característica de cardinalidad intermedia entre barrios y distritos que agrupe barrios similares y que resulte más representativa para el estudio.

In [8]:
km = KModes(n_clusters=15, init='Huang', n_init=10, random_state=42)
df['nb_cluster'] = km.fit_predict(df[['price_med_occupation_per_accommodate', 'neighbourhood']])
clusters = df['nb_cluster'].copy()
df['nb_cluster'] = df['nb_cluster'].apply(lambda x: 'nb_' + str(x))
df.drop(['price_med_occupation_per_accommodate'], axis=1, inplace=True) # solo era para calcular clusters
In [9]:
cluster_map = pd.DataFrame(list(zip(df['neighbourhood'], clusters)), columns=['nb', 'cluster'])
cluster_map.drop_duplicates(inplace=True)

with open('src/geo/' + city + '.neighbourhoods.geojson') as f:
    city_nb = fix_geojson(json.load(f))
    
fig = go.Figure(go.Choroplethmapbox(
    geojson=city_nb,
    locations=cluster_map['nb'], 
    z=cluster_map['cluster'],                   
    colorscale=px.colors.qualitative.Vivid,                                
    marker_opacity=0.5, 
    marker_line_width=0.2
))

fig.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0},
    title='clusters',
    showlegend=False
)

fig.show()

Celdas S2

In [10]:
def get_s2(lat, lng):
    py_cellid = s2.CellId.from_lat_lng(
        s2.LatLng.from_degrees(lat, lng)
    )
    py_cellid = py_cellid.parent(12)
    # lvl2 = py_cellid.level()
    # return py_cellid
    return 's2_' + str(py_cellid.id())

df['s2'] = df.apply(lambda r: get_s2(r['latitude'], r['longitude']), axis=1)
In [11]:
df_s2 = df[['s2', 'latitude', 'longitude']]
s2_cells = sorted(df_s2['s2'].unique())
random.shuffle(s2_cells)
df_s2['idx'] = df_s2['s2'].apply(lambda x: s2_cells.index(x))
In [12]:
fig314 = go.Figure()

fig314.add_trace(go.Scattermapbox(
    lon=df_s2['longitude'],
    lat=df_s2['latitude'],
    mode='markers',
    marker_color=df_s2['idx'],
    text=df_s2['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig314.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig314.show()

Regiones Voronoi

In [13]:
poi_coords = list(map(lambda x: x['coord'], pois))
vor = spatial.Voronoi(poi_coords)

def get_voronoi_index(row):
    new_point = [row['latitude'], row['longitude']]
    point_index = np.argmin(np.sum((vor.points - new_point)**2, axis=1))
    return 'v_' + str(point_index)

df['voronoi'] = df.apply(lambda r: get_voronoi_index(r), axis=1)
spatial.voronoi_plot_2d(vor)
Out[13]:
In [14]:
df_voronoi = df[['voronoi', 'latitude', 'longitude']]
voronoi_cells = sorted(df_voronoi['voronoi'].unique())
df_voronoi['idx'] = df_voronoi['voronoi'].apply(lambda x: voronoi_cells.index(x))
In [15]:
fig315 = go.Figure()

fig315.add_trace(go.Scattermapbox(
    lon=df_voronoi['longitude'],
    lat=df_voronoi['latitude'],
    mode='markers',
    marker_color=df_voronoi['idx'],
    text=df_voronoi['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig315.add_trace(
    go.Scattermapbox(
        lat=list(map(lambda x: x['coord'][0], pois)),
        lon=list(map(lambda x: x['coord'][1], pois)),
        text=list(map(lambda x: x['name'], pois)),
        mode='markers',
        marker=dict(
            size=8,
            opacity=0.9,
            color='black'
        )
    )
)

fig315.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig315.show()

Conversión de características categóricas en dummies

In [16]:
print(df.shape)
dfd = pd.get_dummies(df)
print(dfd.shape)

target = 'price'
features = list(dfd.columns)
features.remove(target)
(13363, 61)
(13363, 303)

Partición en conjuntos de entrenamiento y test

In [17]:
x_train, x_test, y_train, y_test = train_test_split(
    dfd[features], 
    dfd[target],
    test_size=0.3,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings

Modelo base: Random Forest

In [18]:
def eval_model(method, cols, df):
    model = RandomForestRegressor(random_state=42, n_estimators=250)
    """
    model = cb.CatBoostRegressor(
        verbose=0, 
        random_seed=42, 
        depth=10, 
        iterations=150, 
        learning_rate=0.1
    )
    """
    
    regressor = Pipeline([('model', model)])
    regressor.fit(x_train[cols], y_train)
    y_pred = regressor.predict(x_test[cols])
    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)
    mse = mean_squared_error(y_test, y_pred)
    
    collect_results(cols, model, method, r2, mae, mse, skip_coef=True)
    importances = regressor.named_steps['model'].feature_importances_
    print_feature_importances(method, importances, df[cols])
    return y_pred

Estudio de la localización

In [19]:
neighbourhood_cols = [col for col in dfd if col.startswith('neighbourhood')]
dist_cols = [col for col in dfd if col.startswith('dist_')]
coord_cols = ['latitude', 'longitude']
nb_cluster_cols = [col for col in dfd if col.startswith('nb_cluster_')]
s2_cols = [col for col in dfd if col.startswith('s2_')]
voronoi_cols = [col for col in dfd if col.startswith('voronoi')]

Modelo sin variable geográfica

Este modelo registraría toda la variabilidad de precio que es debida a las propiedades de las viviendas sin considerar caractarísticas geográficas de ningún tipo.

In [20]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NO-GEO', cols, dfd)
NO-GEO
MAE 15.638
MSE 650.222
R2 0.703

Residuos

Se busca si existen zonas con un error positivo o negativo.

  • Lo que se puede asociar con puntos de interés: positivo
  • Zonas que los visitantes prefieren evitar: negativo
In [21]:
x_test['resid'] = y_test - y_pred
plt.hist(x_test['resid'], bins=50)
plt.show()

Residuos outliers

In [22]:
x_test2 = x_test.copy()
x_test2.reset_index(inplace=True)
outliers_idx = get_outliers_iqr(x_test2['resid'])[0]
remove_outliers(x_test2, outliers_idx, 'resid')
outliers between following bounds: -38.94120000000005 32.943600000000075
369 outliers to be removed with values: [-225.83879999999994, -152.11079999999993, -141.1635, -129.17880000000008, -115.00559999999999, -98.65440000000004, -94.43159999999995, -93.06719999999987, -92.43359999999996, -89.42759999999993, -86.78159999999994, -84.52800000000002, -84.35519999999985, -84.25799999999992, -82.38599999999997, -81.07559999999981, -77.69159999999997, -77.4765000000001, -76.3994999999999, -74.1708, -72.58319999999975, -70.88399999999997, -70.26479999999987, -70.11719999999994, -69.56639999999987, -69.46199999999988, -69.26159999999994, -68.64839999999994, -68.51879999999991, -68.2956, -68.20559999999983, -67.62959999999983, -67.39199999999997, -66.79822142857137, -66.543, -65.66399999999996, -65.22840000000001, -64.23839999999997, -64.15559999999998, -63.68759999999989, -63.18719999999993, -62.68320000000001, -62.577657142856935, -62.41319999999997, -61.66440000000003, -61.38719999999993, -59.0616, -59.02559999999994, -59.00759999999996, -58.874399999999994, -58.42799999999994, -58.31280000000001, -58.247999999999905, -57.77639999999995, -57.71519999999998, -57.4884, -57.45240000000001, -57.430800000000076, -57.36599999999996, -57.26159999999987, -56.80530000000017, -56.48040000000006, -56.44080000000005, -56.354399999999984, -56.21399999999994, -56.06880000000001, -55.60560000000003, -54.82440000000004, -54.208799999999925, -53.93520000000018, -53.780400000000036, -53.53739999999999, -53.11439999999993, -53.10719999999998, -52.9344, -52.57709999999989, -52.54199999999997, -52.430399999999935, -52.387200000000036, -51.72239999999995, -51.52680000000004, -51.10200000000002, -50.803200000000004, -49.44919999999988, -49.33800000000001, -49.287599999999976, -48.99600000000015, -48.72240000000002, -48.39839999999995, -48.35520000000001, -48.333599999999976, -48.031199999999956, -47.95199999999994, -47.75040000000001, -47.63160000000002, -47.05920000000003, -47.034000000000006, -46.98359999999995, -46.886399999999924, -46.609199999999944, -46.59900000000002, -46.46483142857145, -46.34568, -45.95760000000004, -45.48959999999998, -45.46439999999993, -44.639999999999816, -44.57519999999989, -44.4924, -44.25839999999998, -43.858799999999974, -43.66800000000006, -43.33896, -43.33680000000004, -43.28999999999981, -42.973199999999956, -42.91560000000001, -42.7716, -42.71039999999999, -42.609599999999936, -42.26040000000003, -42.0012, -41.875199999999964, -41.76180000000001, -41.63310000000003, -41.4935999999999, -41.396399999999986, -41.19840000000005, -41.11020000000003, -41.043599999999984, -40.93560000000001, -40.834799999999944, -40.798800000000014, -40.69439999999999, -40.687199999999976, -40.47840000000001, -40.46039999999998, -40.37580000000009, -40.005599999999944, -40.003199999999936, -39.743999999999986, -39.714, -39.59999999999985, -39.56040000000003, -39.286799999999914, -39.02849999999994, 32.95619999999995, 33.087600000000066, 33.10079999999995, 33.13157142857149, 33.24239999999996, 33.34500000000003, 33.35040000000002, 33.59771999999999, 33.64559999999999, 33.742800000000045, 33.78240000000004, 33.793199999999985, 33.9516, 33.95339999999993, 34.12080000000003, 34.12080000000009, 34.21439999999998, 34.31519999999998, 34.45919999999998, 34.502400000000065, 34.959599999999966, 35.02800000000002, 35.34840000000003, 35.38080000000002, 35.51399999999995, 35.60040000000015, 35.767799999999944, 35.77680000000002, 35.92619999999998, 35.92620000000008, 35.928, 35.92800000000004, 36.183599999999984, 36.35999999999994, 37.06920000000004, 37.180799999999955, 37.351414285714284, 37.586800000000096, 37.7136, 38.02079999999994, 38.03880000000001, 38.05559999999997, 38.05560000000003, 38.10006, 38.18879999999996, 38.27520000000001, 38.57399999999997, 38.660399999999996, 38.79719999999999, 39.4122857142857, 39.495599999999996, 39.90240000000007, 39.94919999999999, 40.04519999999998, 40.46400000000001, 40.629600000000096, 41.35680000000008, 41.385600000000125, 41.516099999999966, 41.58000000000007, 41.72040000000028, 41.86080000000004, 42.06805714285714, 42.31391999999995, 42.415800000000004, 42.56279999999998, 42.66720000000001, 42.809862857142775, 43.131600000000006, 43.19279999999998, 43.25760000000007, 43.333200000000005, 43.47720000000007, 43.58160000000001, 43.69319999999999, 43.886399999999966, 44.173800000000014, 44.24039999999991, 44.39519999999993, 44.5536000000001, 44.86680000000011, 44.88839999999999, 45.057599999999994, 45.201600000000155, 45.41399999999999, 46.34160000000003, 46.526400000000095, 46.645199999999946, 47.12039999999993, 47.14920000000001, 47.19239999999999, 47.35440000000008, 47.93760000000003, 48.1032, 48.65760000000003, 48.93119999999996, 49.21920000000006, 49.28490000000001, 49.88879999999999, 50.18399999999996, 50.212800000000044, 50.284800000000004, 50.82659999999999, 50.96304000000001, 51.04079999999998, 51.307199999999995, 51.35310000000021, 51.44040000000044, 51.96240000000007, 52.18289999999999, 52.37279999999997, 52.480799999999974, 52.6374, 53.15399999999997, 53.26632000000001, 54.0864, 54.386999999999986, 55.47959999999999, 55.79845, 56.30039999999998, 56.332800000000034, 56.37959999999998, 56.419200000000004, 56.8584, 57.49560000000001, 57.945599999999985, 58.05, 58.74119999999999, 59.28839999999996, 59.59440000000001, 59.770800000000065, 59.990399999999994, 60.084000000000046, 60.735600000000005, 60.82920000000004, 61.887600000000035, 62.24040000000002, 62.73569999999998, 63.69191999999998, 63.989999999999945, 64.63439999999997, 64.67220000000006, 64.71959999999997, 64.99439999999998, 65.4174857142857, 66.63239999999996, 67.43880000000016, 67.61484000000007, 69.50520000000009, 70.60938000000007, 71.20440000000013, 73.36799999999995, 73.69640000000018, 74.03417999999995, 74.5992, 75.36240000000006, 76.05089999999976, 76.27320000000006, 76.27950000000003, 76.6548, 77.08679999999998, 77.84639999999979, 79.11720000000003, 79.34759999999999, 80.3591999999997, 82.2240000000001, 83.27520000000004, 83.86559999999997, 84.47879999999998, 84.49559999999995, 88.22160000000002, 88.72739999999997, 89.74080000000004, 91.30865000000001, 93.52167818181823, 94.58640000000003, 94.76279999999991, 95.97600000000011, 98.36280000000008, 98.9136, 99.96299999999998, 101.08800000000008, 101.58480000000003, 103.84199999999996, 104.89365, 105.98399999999998, 107.80200000000009, 108.02520000000004, 108.46799999999996, 109.99799999999999, 110.03040000000001, 110.40480000000002, 110.99520000000004, 111.14280000000012, 111.90600000000002, 112.12200000000013, 113.71740000000008, 115.29360000000003, 115.53839999999997, 116.6148, 117.64080000000001, 117.83159999999998, 118.51920000000001, 120.0204, 121.47840000000008, 122.18040000000005, 129.83039999999994, 131.31720000000044, 131.5944, 135.09000000000012, 139.68540000000013, 140.63065714285722, 144.83159999999998, 145.34640000000002, 149.3207999999998, 149.78880000000007, 156.21120000000002, 159.05160000000006, 161.1827999999999, 162.15120000000007, 170.73720000000003, 243.05760000000004, 262.8216]
In [23]:
plt.hist(x_test2['resid'], bins=30)
plt.show()
In [24]:
fig1 = go.Figure(
    go.Scattermapbox(
        lon=x_test2['longitude'],
        lat=x_test2['latitude'],
        mode='markers',
        marker_color=x_test2['resid'],
        text=x_test2['resid'],
        marker=dict(
            opacity=0.8,
            colorscale=[
                [0.0, "rgb(165,0,38)"],
                [0.11, "rgb(215,48,39)"],
                [0.22, "rgb(244,109,67)"],
                [0.33, "rgb(253,174,97)"],
                [0.44, "rgb(254,224,144)"],
                [0.55, "rgb(224,243,248)"],
                [0.66, "rgb(171,217,233)"],
                [0.77, "rgb(116,173,209)"],
                [0.88, "rgb(69,117,180)"],
                [1.0, "rgb(49,54,149)"]
            ]
        )
    )
)

fig1.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':x_test2['latitude'].mean(), 'lon':x_test2['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig1.show()

Coordenadas

In [25]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('COORD', cols, dfd)
NO-GEO COORD
R2 0.703 0.722
MAE 15.638 14.892
MSE 650.222 609.434

Barrios

In [26]:
cols = features.copy()
for c in [*dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NB', cols, dfd)
NO-GEO COORD NB
R2 0.703 0.722 0.709
MAE 15.638 14.892 15.132
MSE 650.222 609.434 638.361

Cluster de barrios

In [27]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('CLUSTER-NB', cols, dfd)
NO-GEO COORD NB CLUSTER-NB
R2 0.703 0.722 0.709 0.707
MAE 15.638 14.892 15.132 15.381
MSE 650.222 609.434 638.361 641.000

Distancias a puntos de interés

In [28]:
cols = features.copy()
for c in [*neighbourhood_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('DIST', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST
R2 0.703 0.722 0.709 0.707 0.709
MAE 15.638 14.892 15.132 15.381 15.305
MSE 650.222 609.434 638.361 641.000 636.975

Voronoi

In [29]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *s2_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('VORONOI', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI
R2 0.703 0.722 0.709 0.707 0.709 0.713
MAE 15.638 14.892 15.132 15.381 15.305 15.191
MSE 650.222 609.434 638.361 641.000 636.975 628.187

S2

In [30]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('S2', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2
R2 0.703 0.722 0.709 0.707 0.709 0.713 0.714
MAE 15.638 14.892 15.132 15.381 15.305 15.191 15.119
MSE 650.222 609.434 638.361 641.000 636.975 628.187 626.751

Balanceo undersampling por cluster de barrios

In [31]:
df_us = df.copy().sample(frac=1, random_state=42)
df_us.shape
Out[31]:
(13363, 61)
In [32]:
def get_max_sample_size(df):
    df_by_cluster = df_us.groupby(['nb_cluster'])['nb_cluster'].count().to_frame('count')
    df_by_cluster.reset_index(inplace=True)
    return min(df_by_cluster['count'])

def print_cluster_dist(df):
    df_by_cluster = df.groupby(['nb_cluster'])['nb_cluster'].count().to_frame('count')
    df_by_cluster.reset_index(inplace=True)
    df_by_cluster.sort_values(by=['count'], inplace=True)
    fig = px.bar(df_by_cluster, x='nb_cluster', y='count')
    fig.show()
In [33]:
print_cluster_dist(df_us)

for c in [12, 5, 13, 8, 9, 14, 11, 10, 3]:
    val = 'nb_' + str(c)
    df_us['nb_cluster'][df_us['nb_cluster'] == val] = 'nb_other'
    
print_cluster_dist(df_us)
In [34]:
sample_size = get_max_sample_size(df_us)
print(sample_size)
parts = []

for c in np.unique(df_us['nb_cluster']):
    x_tmp = df_us.loc[df_us['nb_cluster'] == c].sample(n=sample_size, random_state=42)
    parts.append(x_tmp)
    
df_us = pd.concat(parts)

print_cluster_dist(df_us)
785
In [35]:
df_us = pd.get_dummies(df_us)

cols = list(df_us.columns).copy()
for c in [*neighbourhood_cols, *coord_cols, *dist_cols, *voronoi_cols, *s2_cols]:
    if c in cols:
        cols.remove(c)

target = 'price'
features = list(cols)
features.remove(target)
In [36]:
x_train, x_test, y_train, y_test = train_test_split(
    df_us[features], 
    df_us[target],
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings
In [37]:
y_pred = eval_model('CLUSTER-UNDERSAMP', features, df_us)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2 CLUSTER-UNDERSAMP
R2 0.703 0.722 0.709 0.707 0.709 0.713 0.714 0.645
MAE 15.638 14.892 15.132 15.381 15.305 15.191 15.119 16.808
MSE 650.222 609.434 638.361 641.000 636.975 628.187 626.751 770.116

Automated feature engineering

In [38]:
auto_df = df.copy()
auto_df['auto_id'] = auto_df['price'].apply(lambda x: uuid.uuid1().int)
prices = auto_df['price']
auto_df.drop(['price'], axis=1, inplace=True, errors='ignore')
In [39]:
es = ft.EntitySet(id='airbnb')
es = es.entity_from_dataframe(
    entity_id='main',
    dataframe=auto_df,
    index='auto_id'
)
In [40]:
# available_transform_primitives = ft.primitives.list_primitives()
# print(available_transform_primitives[available_transform_primitives['type'] == 'transform'])

features_df, feature_names = ft.dfs(
    entityset=es,
    target_entity='main',
    trans_primitives=['subtract_numeric'],
    max_depth=2
)

# print(features_df.columns)
In [41]:
auto_df = features_df.copy()
auto_df.reset_index()
auto_df.drop(['auto_id'], axis=1, inplace=True, errors='ignore')

auto_df = pd.get_dummies(auto_df)
print(auto_df.shape)

auto_features = list(auto_df.columns)

x_train, x_test, y_train, y_test = train_test_split(
    auto_df, 
    prices,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings
(13363, 1680)
In [42]:
y_pred = eval_model('AUTO-FT', auto_features, auto_df)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2 CLUSTER-UNDERSAMP AUTO-FT
R2 0.703 0.722 0.709 0.707 0.709 0.713 0.714 0.645 0.697
MAE 15.638 14.892 15.132 15.381 15.305 15.191 15.119 16.808 15.191
MSE 650.222 609.434 638.361 641.000 636.975 628.187 626.751 770.116 655.826